package com.qf.java2105.huangchuang.hotel.controller.food;

import com.alibaba.druid.util.StringUtils;
import com.qf.java2105.huangchuang.hotel.constant.MessageConstant;
import com.qf.java2105.huangchuang.hotel.constant.ResponseMessageConstant;
import com.qf.java2105.huangchuang.hotel.controller.BaseServlet;
import com.qf.java2105.huangchuang.hotel.entity.ResultVO;
import com.qf.java2105.huangchuang.hotel.pojo.Food;
import com.qf.java2105.huangchuang.hotel.pojo.FoodType;
import com.qf.java2105.huangchuang.hotel.utils.JsonUtils;
import com.qf.java2105.huangchuang.hotel.utils.UploadFileUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 菜品方法控制
 * @author hcvg
 * @version v1.0
 * @date 2021/09/13
 **/
@WebServlet("/food")
@MultipartConfig
public class FoodController extends BaseServlet {
//    IFoodService foodService = (IFoodService) BeanFactory.getBean("foodService");
//    IFoodTypeService foodTypeService = (IFoodTypeService) BeanFactory.getBean("foodTypeService");

    /*@Override
    public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String method = request.getParameter("method");
        switch (method){
            case "delete":
                this.delete(request,response);
                break;
            case "save":
                this.save(request,response);
                break;
            case "saveui":
                this.saveui(request,response);
                break;
            case "search":
                this.search(request,response);
                break;
            case "update":
                this.update(request,response);
                break;
            case "updateui":
                this.updateui(request,response);
                break;
            default:
                response.getWriter().write(MessageConstant.REQUEST_ERROR);
                return;
        }

    }
*/

    /**
     * 菜品删除
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    private String delete(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        ResultVO<String> resultVO = null;
        try {
            String idStr = request.getParameter("id");
            if (!StringUtils.isEmpty(idStr)){
                resultVO = FOOD_SERVICE.deleteById(Integer.valueOf(idStr));
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return "<script>alert('" + resultVO.getMessage() + "'); location.href = \"/food?method=search\"</script>";
        }
        // 删除后
        return ResponseMessageConstant.PREFIX_REDIRECT + request.getContextPath() + "/food?method=search";

    }

    /**
     * 菜品保存
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    private String save(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        ResultVO<String> resultVO = null;
        try {
            // 上传文件
            String foodImagesPath = UploadFileUtils.uploadFile(request, "imageUrl", request.getContextPath() + "/images/food/");

            // 获取前台数据
            Map<String, String[]> parameterMap = request.getParameterMap();
            Food food = new Food();
            // BeanUtils封装
            BeanUtils.populate(food, parameterMap);

            // 查看菜品名称是否存在
            if (StringUtils.isEmpty(food.getFoodName())){
                return "<script>alert('" + MessageConstant.NO_FOOD_NAME + "'); location.href = \"/food?method=search\"</script>";
            }
            // 将上传的图片对应到菜品中
            food.setFoodImage(foodImagesPath);

            resultVO = FOOD_SERVICE.save(food);
            if (resultVO.getSuccess()){
                // 更新菜品成功跳转到菜品列表页,本质上是去查询所有菜品
                return ResponseMessageConstant.PREFIX_REDIRECT + request.getContextPath() + "/food?method=search";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "<script>alert('" + MessageConstant.NO_FOOD_DETAIL + "'); location.href = \"/food?method=search\"</script>";
        }
        return "<script>alert('" + resultVO.getMessage() + "'); location.href = \"/food?method=search\"</script>";
    }

    /**
     * 菜品保存页面
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    private String saveui(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        ResultVO<List<FoodType>> resultVO = FOOD_TYPE_SERVICE.findByFoodTypeName(null);
        request.setAttribute("foodtypes", resultVO.getData());
        return ResponseMessageConstant.PREFIX_FORWARD + request.getContextPath() + "/backend/detail/food/food-save.jsp";
    }

    /**
     * 菜品通用查询
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    private String search(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        String keyword = request.getParameter("keyword");
        ResultVO<List<Food>> resultVO = FOOD_SERVICE.findByFoodName(keyword);

        request.setAttribute("keyword", keyword == null ? "" : keyword.trim());
        request.setAttribute("foods", resultVO.getData());
        return ResponseMessageConstant.PREFIX_FORWARD + request.getContextPath() + "/backend/detail/food/food-list.jsp";
    }

    /**
     * 菜品更新
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    private String update(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        ResultVO<String> resultVO = null;
        try {
            // 上传文件
            String id = request.getParameter("id");
            String typeId = request.getParameter("cid");
            String foodImagesPath = UploadFileUtils.uploadFile(request, "imageUrl", request.getContextPath() + "/images/food/");
            // 获取前台需要更新的数据
            Map<String, String[]> parameterMap = request.getParameterMap();
            Food food = new Food();
            // BeanUtils封装
            BeanUtils.populate(food, parameterMap);
            food.setFoodId(Integer.valueOf(id));
            food.setTypeId(Integer.valueOf(typeId));
            // 将上传的图片对应到菜品中
            // 如果更新时没有传入图片，则用数据库以保存的图片，传入图片则更新图片
            if ("".equals(foodImagesPath)){
                ResultVO<Food> foodResultVO = FOOD_SERVICE.findById(Integer.valueOf(id));
                foodImagesPath = foodResultVO.getData().getFoodImage();
                food.setFoodImage(foodImagesPath);
            }else {
                food.setFoodImage(foodImagesPath);
            }

            if (StringUtils.isEmpty(food.getFoodName())){
                return "<script>alert('" + MessageConstant.NO_FOOD_NAME + "'); location.href = \"/food?method=search\"</script>";
            }
            resultVO = FOOD_SERVICE.update(food);

            if (resultVO.getSuccess()){
                // 添加菜品成功跳转到菜品列表页,本质上是去查询所有菜品
                return ResponseMessageConstant.PREFIX_REDIRECT + request.getContextPath() + "/food?method=search";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "<script>alert('" + resultVO.getMessage() + "'); location.href = \"/food?method=search\"</script>";
    }

    /**
     * 菜品更新页面
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    private String updateui(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        // 查询菜系列表
        ResultVO<List<FoodType>> resultVO = FOOD_TYPE_SERVICE.findByFoodTypeName(null);
        request.setAttribute("foodTypes", resultVO.getData());
        // 通过回传的菜品id查询此菜品
        String idStr = request.getParameter("id");
        if (!StringUtils.isEmpty(idStr)){
            ResultVO<Food> foodResultVO = FOOD_SERVICE.findById(Integer.valueOf(idStr));
            request.setAttribute("food", foodResultVO.getData());
        }
        return ResponseMessageConstant.PREFIX_FORWARD + request.getContextPath() + "/backend/detail/food/food-update.jsp";
    }

    /**
     * ajax异步验证菜品名是否已经存在
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    private String foodNameExist (HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        String foodName = request.getParameter("foodName");
        ResultVO<Food> resultVO = FOOD_SERVICE.foodNameExist(foodName);
        return JsonUtils.objectToJson(resultVO);
    }






}
